<?php

function check_verify($code, $id=''){
	
	$verify = new \Think\Verify();
	
	return $verify->check($code, $id);
	
}

function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0){
	
	$tree = array();
	
	if(is_array($list)){
		
		$refer = array();
		
		foreach($list as $key => $data){
			
			$refer[$data[$pk]] = &$list[$key];
			
		}
		
		foreach($list as $key => $data){
			
			$parentId =  $data[$pid];
			
			if($root == $parentId){
				
				$tree[] = &$list[$key];
				
			}else{
				
				if(isset($refer[$parentId])){
					
					$parent = &$refer[$parentId];
					
					$parent[$child][] = &$list[$key];
					
				}
				
			}
			
		}
		
	}
	
	return $tree;
	
}

function get_username($uid = 0){
    static $list;
    if(!($uid && is_numeric($uid))){
        return session('memberinfo.username');
    }

    if(empty($list)){
        $list = S('sys_user_username_list');
    }

    $key = "u{$uid}";
    if(isset($list[$key])){
        $name = $list[$key];
    } else {
        $info = M('Member')->field('username')->find($uid);
        if($info !== false && $info['username'] ){
            $username = $info['username'];
            $name = $list[$key] = $username;
            $count = count($list);
            $max   = C('USER_MAX_CACHE');
            while ($count-- > $max) {
                array_shift($list);
            }
            S('sys_user_username_list', $list);
        } else {
            $name = '';
        }
    }
    return $name;
}

function action_log($action = null, $model = null, $record_id = null, $user_id = null){

	if(empty($action) || empty($model) || empty($record_id)){
        return '参数不能为空';
    }
    if(empty($user_id)){
        $user_id = is_login();
    }

    $action_info = M('Action')->getByName($action);
	
	if(empty($action_info['id'])){
		$source = array(
		
		
		);
	}
	
    if($action_info['status'] != 1){
        return '该行为被禁用或删除';
    }

    $data['action_id']      =   $action_info['id'];
    $data['user_id']        =   $user_id;
    $data['action_ip']      =   ip2long(get_client_ip());
    $data['model']          =   $model;
    $data['record_id']      =   $record_id;
    $data['create_time']    =   NOW_TIME;

    if(!empty($action_info['log'])){
        if(preg_match_all('/\[(\S+?)\]/', $action_info['log'], $match)){
            $log['user']    =   $user_id;
            $log['record']  =   $record_id;
            $log['model']   =   $model;
            $log['time']    =   NOW_TIME;
            $log['data']    =   array('user'=>$user_id,'model'=>$model,'record'=>$record_id,'time'=>NOW_TIME);
            foreach ($match[1] as $value){
                $param = explode('|', $value);
                if(isset($param[1])){
                    $replace[] = call_user_func($param[1],$log[$param[0]]);
                }else{
                    $replace[] = $log[$param[0]];
                }
            }
            $data['remark'] = str_replace($match[0], $replace, $action_info['log']);
        }else{
            $data['remark'] = $action_info['log'];
        }
    }else{
        $data['remark'] = '操作url：'.$_SERVER['REQUEST_URI'];
    }

    M('ActionLog')->add($data);

    if(!empty($action_info['rule'])){
        $rules = parse_action($action, $user_id);
        $res = execute_action($rules, $action_info['id'], $user_id);
    }
}


function parse_action($action = null, $self){
    if(empty($action)){
        return false;
    }

    if(is_numeric($action)){
        $map = array('id'=>$action);
    }else{
        $map = array('name'=>$action);
    }

    $info = M('Action')->where($map)->find();
    if(!$info || $info['status'] != 1){
        return false;
    }

    $rules = $info['rule'];
    $rules = str_replace('{$self}', $self, $rules);
    $rules = explode(';', $rules);
    $return = array();
    foreach ($rules as $key=>&$rule){
        $rule = explode('|', $rule);
        foreach ($rule as $k=>$fields){
            $field = empty($fields) ? array() : explode(':', $fields);
            if(!empty($field)){
                $return[$key][$field[0]] = $field[1];
            }
        }
        if(!array_key_exists('cycle', $return[$key]) || !array_key_exists('max', $return[$key])){
            unset($return[$key]['cycle'],$return[$key]['max']);
        }
    }

    return $return;
}

function execute_action($rules = false, $action_id = null, $user_id = null){
    if(!$rules || empty($action_id) || empty($user_id)){
        return false;
    }

    $return = true;
    foreach ($rules as $rule){

        $map = array('action_id'=>$action_id, 'user_id'=>$user_id);
        $map['create_time'] = array('gt', NOW_TIME - intval($rule['cycle']) * 3600);
        $exec_count = M('ActionLog')->where($map)->count();
        if($exec_count > $rule['max']){
            continue;
        }

        $Model = M(ucfirst($rule['table']));
        $field = $rule['field'];
        $res = $Model->where($rule['condition'])->setField($field, array('exp', $rule['rule']));

        if(!$res){
            $return = false;
        }
    }
    return $return;
}

function time_format($time = NULL,$format='Y-m-d H:i'){
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}

?>